package com.jqb.dom;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.junit.Test;

public class Dom4j {
	@Test
	public void testDom4j() throws Exception {
		dom4jParse();
		dom4jCreate();
	}

	@SuppressWarnings("unchecked")
	public static void dom4jParse() throws DocumentException {
		/*--->parse<---*/
		SAXReader reader = new SAXReader();
		Document doc = reader.read(new File("src/test/resources/users.xml"));
		Element users = doc.getRootElement();
		Iterator<Element> iter = users.elementIterator();
		while(iter.hasNext()){
			Element user = iter.next();
			System.out.print("id="+user.attribute("id").getText());
			System.out.println(" name="+user.element("name").getText());
		}
	}

	public static void dom4jCreate() throws UnsupportedEncodingException,
			IOException {
		/*--->create<---*/
		/*创建节点的过程就拼接好了*/
		Document doc = DocumentHelper.createDocument();
		Element users = doc.addElement("users");
		Element user = users.addElement("user");
		Element name =user.addElement("name");
		name.setText("admin1000");
		user.addAttribute("id", "1000");
		/*设置输出格式*/
		OutputFormat format = OutputFormat.createPrettyPrint();
		format.setEncoding("utf-8");
		/*输出*/
		XMLWriter writer = new XMLWriter(System.out,format);
		writer.write(doc);
	}
}
